package com.lianxi.es;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.Node;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsConfig {

    private Logger logger = LoggerFactory.getLogger(EsConfig.class);
    @Value("${es_host}")
    private String host;
    @Value("${es_hosts}")
    private String hosts;
    @Value("${es_ports}")
    private String ports;
    @Value("${es_username}")
    private String username;
    @Value("${es_password}")
    private String password;

    @Bean
    public RestHighLevelClient client(){
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials(
                        username,
                        password
                )
        );
        if (StringUtils.isBlank(host)) {
            String[] hostArr = hosts.split(",");
            String[] portArr = ports.split(",");
            Node[] nodes = new Node[hostArr.length];
            for (int i = 0; i < hostArr.length; i++) {
                nodes[i] = new Node(new HttpHost(hostArr[i], Integer.parseInt(portArr[i])));
            }
            RestHighLevelClient client = new RestHighLevelClient(
                    RestClient.builder(nodes).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)));
            logger.info("《《《《《《《元数据Es初始化成功》》》》》》》");
            return client;
        }
        if (StringUtils.isNotBlank(host)) {
            RestHighLevelClient client = new RestHighLevelClient(
                    RestClient.builder(new HttpHost(host, 9200, "http")).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)));
            logger.info("《《《《《《《元数据Es初始化成功》》》》》》》");
            logger.info(host);
            return client;
        }
        return null;
    }

    @Bean
    public RestClient lowClient(){
        return client().getLowLevelClient();
    }

}
